<template>
    <div>
        <el-card>
            <!-- 行内表单 -->
            <div slot="header">
                <el-form v-model="formTypeList" :inline="true" class="demo-form-inline">
                    <el-form-item label="设备名称">
                        <el-input v-model="formTypeList.deviceName" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="设备分类">
                        <el-select v-model="formTypeList.selectValue" placeholder="请选择--">
                            <el-option label="请选择--" value=""></el-option>
                            <el-option
                                v-for="(item, index) in dependencyList.deviceTypeList"
                                :key="index"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="warning" icon="el-icon-search" @click="searchDeviceList">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-plus" @click="add">添加设备</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 主体部分的表格 -->
            <el-table :data="tableData" style="width: 100%" :current-row-key="tableData.id">
                <el-table-column
                    type="index"
                    label="编号"
                    width="50"
                >
                </el-table-column>
                <el-table-column label="名称">
                    <template slot-scope="slotProps">
                        {{slotProps.row.name}}
                    </template>
                </el-table-column>
                <el-table-column label="型号">
                    <template slot-scope="slotProps">
                        {{slotProps.row.model}}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间">
                    <template slot-scope="slotProps">
                        {{slotProps.row.createTime}}
                    </template>
                </el-table-column>
                <el-table-column label="所属部门">
                    <template slot-scope="slotProps">
                        {{slotProps.row.departmentName}}
                    </template>
                </el-table-column>
                <el-table-column label="关联实验室">
                    <template slot-scope="slotProps">
                        {{slotProps.row.addressName}}
                    </template>
                </el-table-column>
                <el-table-column label="类别">
                    <template slot-scope="slotProps">
                        {{slotProps.row.typeName}}
                    </template>
                </el-table-column>
                <el-table-column label="单价">
                    <template slot-scope="slotProps">
                        {{`${slotProps.row.price}元`}}
                    </template>
                </el-table-column>
                <el-table-column label="数量">
                    <template slot-scope="slotProps">
                        {{`${slotProps.row.count}件`}}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160">
                    <template slot-scope="slotProps">
                        <el-button type="primary" size="mini" title="编辑" icon="el-icon-edit" @click="edit(slotProps.$index)"></el-button>
                        <el-button type="danger" size="mini" title="删除" icon="el-icon-delete" @click="del(slotProps.$index)"></el-button>
                        <!-- <router-link :to="`/device/adminPageDetail/${slotProps.row.id}`">
                            <el-button type="text">查看</el-button>
                        </router-link> -->
                    </template>
                </el-table-column>
            </el-table>
            <br>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next, jumper"
                    :pager-count="5"
                    :total="page.total"
                    :page-size="page.pageSize"
                    :current-page="page.currentPage"
                    @current-change="handleCurrentChange"
                >
                </el-pagination>
            </div>
        </el-card>
        <!-- 点击删除时的弹框 -->
        <el-dialog
            :title="delDialog.title"
            :visible.sync="delDialog.show"
            width="400px"
            center>
            <span>{{delDialog.content}}</span>
            <span slot="footer">
                <el-button @click="delDialog.show = false">取 消</el-button>
                <el-button type="primary" @click="delSure">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 点击添加、编辑时的弹框 -->
        <el-dialog
            :title="dialog.isEdit?'编辑':'添加'"
            :visible.sync="dialog.show"
            @close="handleDialogClose(`formData`)"
            width="800px"
            center>
            <el-form ref="formData" :rules="ruleForm" :model="formData" label-width="80px">
                <el-form-item label="设备名称" prop="name">
                    <el-input placeholder="请输入设备名称" v-model="formData.name"></el-input>
                </el-form-item>
                <el-form-item label="设备型号" prop="model">
                    <el-input placeholder="请输入设备型号" v-model="formData.model"></el-input>
                </el-form-item>
                <el-form-item label="允许使用" prop="roleids">
                    <el-checkbox-group v-model="formData.roleids" @change="handleCheckboxChange">
                        <el-checkbox
                            v-for="item in dependencyList.userRoleList"
                            :key="item.id"
                            :label="item.id"
                        >
                        {{item.name}}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="设备分类" prop="typeId">
                    <el-select v-model="formData.typeId" placeholder="请选择--">
                        <el-option label="请选择--" value=""></el-option>
                        <el-option
                            v-for="(item, index) in dependencyList.deviceTypeList"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属部门" prop="departmentId">
                    <el-select v-model="formData.departmentId" placeholder="请选择--">
                        <el-option label="请选择--" value=""></el-option>
                        <el-option
                            v-for="(item, index) in dependencyList.departmentList"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="存放地" prop="addressId">
                    <el-select v-model="formData.addressId" placeholder="请选择--">
                        <el-option label="请选择--" value=""></el-option>
                        <el-option
                            v-for="(item, index) in dependencyList.addressList"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量" prop="count" v-if="!dialog.isEdit">
                    <el-input-number v-model="formData.count" controls-position="right" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input placeholder="请输入价格" type="number" v-model="formData.price">
                        <template slot="prepend">￥</template>
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="dialog.show = false">取 消</el-button>
                    <el-button v-if="dialog.isEdit" type="primary" @click="editSure('formData')">提 交</el-button>
                    <el-button v-else type="primary" @click="addSure('formData')">添 加</el-button>
                    <el-button @click="resetForm('formData')">重 置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import request from '@/utils/request'
import { isvalidInt } from '@/utils/validate'
export default {
  data() {
    const validInt = (rule, value, callback) => { // 整数验证
      if (!value) {
        callback(new Error('请输入设备数量'))
      } else if (!isvalidInt(value)) {
        callback(new Error('请输入整数'))
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      page: {
        total: 10,
        pageSize: 10,
        currentPage: 1
      },
      dependencyList: { // 依赖相关
        deviceTypeList: [], // 设备分类列表
        addressList: [], // 存放地列表
        userRoleList: [], // 角色列表
        departmentList: [] // 部门列表
      },
      formTypeList: {
        selectValue: '',
        deviceName: ''
      },
      delDialog: {
        show: false,
        title: '提示',
        content: '您确定要删除当前设备吗？',
        currentId: ''
      },
      dialog: {
        show: false,
        title: '编辑',
        index: '',
        isEdit: false
      },
      formData: {}, // 表单中的数据
      resetData: {}, // 重置表单的数据
      ruleForm: { // 表单验证
        name: [
          { required: true, message: '请输入设备名称', trigger: 'blur' }
        ],
        model: [
          { required: true, message: '请输入设备型号', trigger: 'blur' }
        ],
        roleids: [
          { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
        ],
        typeId: [
          { required: true, message: '请选择设备分类', trigger: 'change' }
        ],
        departmentId: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        addressId: [
          { required: true, message: '请选择存放地', trigger: 'change' }
        ],
        count: [
          { required: true, validator: validInt, trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入设备价格', trigger: 'blur' }
        ]
      }
    }
  },
  // beforeUpdate() {
  //   alert('beforeUpdate')
  // },
  // beforeDestroy() {
  //   alert('beforeDestroy')
  // },
  mounted() {
    // alert('mounted')
    this.getList()
    // 获取下拉框依赖列表，设备分类
    request.get('/items/deviceType').then(res => {
      this.dependencyList.deviceTypeList = res.content
    })
    // 获取下拉框依赖列表，存放地
    request.get('/items/address').then(res => {
      this.dependencyList.addressList = res.content
    })
    // 获取多选框依赖列表，允许使用的角色
    request.get('/ac/userRole').then(res => {
      this.dependencyList.userRoleList = res.content
    })
    // 获取下拉框依赖列表，所属部门
    request.get('/ac/department').then(res => {
      this.dependencyList.departmentList = res.content
    })
  },
  methods: {
    // 翻页器
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    },
    // 初始化列表
    getList(current) {
      request.get('/items/device', { params: {
        size: this.page.pageSize,
        current: this.page.currentPage,
        typeId: this.formTypeList.selectValue,
        name: this.formTypeList.deviceName
      }}).then(res => {
        this.tableData = res.content.records
        this.page.total = res.content.total
      })
    },
    // 根据一定条件查询设备列表
    searchDeviceList() {
      this.getList()
    },
    // 根据id查询详细信息
    getDetail(id) {
      request.get(`/items/device/${id}`).then(res => {
        const { name, model, roleids, typeId, departmentId, addressId, price } = res.content
        this.formData = { name, model, roleids, typeId, departmentId, addressId, price }
        var array = [...this.formData.roleids.replace(/,/g, '')]
        this.formData.roleids = []
        this.formData.roleids = [...array] // 此处得到的数组的元素是字符串
        for (let i = 0; i < this.formData.roleids.length; i++) {
          this.formData.roleids[i] = parseInt(this.formData.roleids[i]) // 将String转换为Number
        }
        this.resetData = { ...this.formData }
      })
    },
    // 删除设备
    del(index) {
      this.delDialog.show = true
      this.delDialog.currentId = this.tableData[index].id
    },
    delSure() {
      request.delete(`/items/device/${this.delDialog.currentId}`).then(() => {
        this.getList()
        this.delDialog.show = false
      })
    },
    // 添加设备
    add() {
      this.formData = {}
      this.$set(this.formData, 'roleids', ['']) // 为data根节点中的数据添加属性，需要使用set方法
      this.dialog.show = true
      this.dialog.isEdit = false
    },
    addSure(formName) {
      const addData = { ...this.formData }
      this.$refs[formName].validate(valid => {
        if (valid) {
          addData.roleids = addData.roleids.join(',')
          request.post('items/device/add', {
            ...addData
          }).then(res => {
            if (res.code === 0) {
              this.getList()
            } else {
              this.$message.error(res.content)
            }
            this.dialog.show = false
          })
        }
      })
    },
    // 编辑某一个设备
    edit(index) {
      this.dialog.show = true
      this.dialog.isEdit = true
      this.dialog.index = index
      this.getDetail(this.tableData[index].id)
    },
    editSure(formName) {
      var editData = { ...this.formData }
      this.$refs[formName].validate(valid => {
        if (valid) { // 若表单内容通过验证规则，则提交表单，反之，不提交
          editData.roleids = editData.roleids.join(',') // 此处得到的是字符串
          request.put('/items/device', {
            id: this.tableData[this.dialog.index].id,
            ...editData
          }).then(res => {
            if (res.code === 0) {
              this.getList()
            } else {
              this.$message.error(res.content)
            }
            this.dialog.show = false
          })
        }
      })
    },
    // Dialog关闭的回调
    handleDialogClose(formName) {
      this.$refs[formName].resetFields()
    },
    // 当多选框的绑定值发生变化后触发的事件 CHeckbox-group Events
    handleCheckboxChange(value) {
      if (!this.dialog.isEdit) { // 添加的时候调用
        this.formData.roleids = [...value]
      }
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields() // 此处用this.$refs[formName].resetFields()后会把表单置空的原因是初始data里的数据就是空的
      this.formData = { ...this.resetData }
    }
  }
}
</script>

<style scoped>
.pagination {
  float: right;
  margin-bottom: 15px;
}
</style>
